/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import QtQuick 2.12
import org.ukui.tablet 1.0
import "./baseComponent"

LauncherGridViewDelegateItem {
    id: itemRoot
    width: modelData.columnSpan * cellSize
    height: modelData.rowSpan * gridCellHeight
    Drag.active: dragMousearea.drag.active && dragEnable
    Drag.hotSpot.y: 0//itemRoot.height / 2
    states: [
        State {
            when: itemRoot.Drag.active
            ParentChange {
                target: itemRoot
                parent: listView
            }

            AnchorChanges {
                target: itemRoot
                anchors.horizontalCenter: undefined
                anchors.top: undefined
            }
        }
    ]

    MouseArea {
        id: dragMousearea
        anchors.fill: parent
        hoverEnabled: true
        Drag.active: false
        drag.target: undefined
        property bool isScrolling: false

        Timer {
            id: scrollingTimer
            interval: 1000
            onTriggered: dragMousearea.isScrolling = false
        }

        onPressAndHold: {
            console.log("press and hold")
            if (itemRoot.pageIndex === 0) {
                return
            }
            dragMousearea.Drag.active = true
            dragMousearea.drag.target = itemRoot
            startDrag(true)
        }
        onClicked: {
            console.log("LauncherView clicked")
            root.titleFocusChanged()
        }
        onPositionChanged:  {
            var itemPos = item.mapToItem(listView, 0, 0)
            if ((itemPos.x % listView.width) >= (listView.width - 100) &&
                    dragMousearea.Drag.active &&!isScrolling ) {
                if (listView.currentIndex < listView.count - 1) {
                    listView.currentIndex ++
                    isScrolling = true
                    scrollingTimer.start()
                    modelManager.addPlaceholderItem(modelManager.launcerPageItemCount(listView.currentIndex),
                                                    listView.currentIndex,
                                                    drag.target.rowSpan,
                                                    drag.target.columnSpan,
                                                    groupId)
                }
            } else if ((itemPos.x % listView.width < 100) &&
                       dragMousearea.Drag.active && !isScrolling) {
                if (listView.currentIndex > 0) {
                    listView.currentIndex --
                    isScrolling = true
                    scrollingTimer.start()
                    modelManager.addPlaceholderItem(modelManager.launcerPageItemCount(listView.currentIndex),
                                                    listView.currentIndex,
                                                    drag.target.rowSpan,
                                                    drag.target.columnSpan,
                                                    groupId)
                }
            }
        }
        onReleased: {
            isScrolling = false
            dragMousearea.Drag.active = false
            dragMousearea.drag.target = null
            modelManager.replacePlaceholderItem(visualIndex, pageIndex)
            startDrag(false)
        }
    }

    Rectangle {
        id: item
        width: modelData.columnSpan * cellSize - Style.widthScaleFactor * 40 + 1
        height: modelData.rowSpan * gridCellHeight - Style.heightScaleFactor * 40 + 1
        color: "transparent"
        clip: true
        radius: 5
        anchors {
            horizontalCenter: parent.horizontalCenter;
            verticalCenter: parent.verticalCenter
        }
        Image {
            id: appIcon
            anchors.fill: parent
            smooth: true
            visible: modelData.type === LauncherItem.AppIcon
            source: modelData.type === LauncherItem.AppIcon ? "file://" + modelData.icon : ""
        }

        Component.onCompleted: {
            if (modelData.type === LauncherItem.Container) {
                itemName.visible = false
                var component = Qt.createComponent("AppContainer.qml");
                if (component.status === Component.Ready) {
                    var titleEditable = modelData.titleEditable

                    var container = component.createObject(item, { width: item.width,
                                                               height: item.height,
                                                               model: modelManager.groupModel(modelData.id),
                                                               containerTitle: modelData.name,
                                                               groupId: modelData.id,
                                                               titleEditable: titleEditable,
                                                               blurWindow: root.blurWindow, rootItem: root.rootItem });

                    container.width = Qt.binding(function() {
                        return item.width
                    })
                    container.height = Qt.binding(function() {
                        return item.height
                    })

                    root.startDrag.connect(container.enableItemDrag)
                    root.titleFocusChanged.connect(container.editFocusChange)
                    container.itemStartDrag.connect(function(start) {
                        dragEnable = !start
                        console.log("item in container start dragging...", start)
                    })
                    container.showAddAppWindow.connect(root.showAddAppWindow)
                } else {
                    console.log("error string: ", component.errorString() )
                }
            } else if (modelData.type === LauncherItem.Group) {
                itemName.visible = false
                var groupcomponent = Qt.createComponent("AppContainer.qml");
                if (groupcomponent.status === Component.Ready) {
                    var group = groupcomponent.createObject(item, { enable: false, scale: Style.widthScaleFactor * 0.2, transformOrigin: Item.TopLeft,
                                                                model: modelManager.groupModel(modelData.id) });
                    group.enableItemDrag(true)
                }
            }
        }
    }
    GridViewDelegateItemText {
        id: itemName
        width: item.width
        anchors.top: item.bottom
        anchors.horizontalCenter: item.horizontalCenter
        visible: modelData.type === LauncherItem.AppIcon
    }
}
